import React, {useState, useEffect} from 'react';
import {Form, Button, Drawer, Input, Select, Spin} from 'antd';
import {connect} from 'dva';
import SelectCron from "@/pages/common/cron/SelectCron";

const { Option } = Select;


/**
 * 新增定时任务
 *
 * @author zhangby
 * @date 28/2/20 10:20 am
 */
function CronAdd(props,ref) {
  const [visible, setVisible] = useState(false);
  const [cron, setCron] = useState('* * * * * ?');
  const { dispatch, cronSelectData, loading } = props;
  const { getFieldDecorator, resetFields, getFieldValue, setFieldsValue } = props.form;

  // 初始化页面
  useEffect(() => {
    if (dispatch){
      dispatch({
        type: 'cron/getCronSelectData',
      });
    }
  },[])

  // 初始化
  const initAdd = () => {
    resetFields();
    setVisible(true);
  }

  // 提交
  const onsubmit = () => {
    props.form.validateFieldsAndScroll((err, values) => {
      // eslint-disable-next-line no-empty
      if (!err) {
        values['cron'] = cron;
        if (dispatch){
          dispatch({
            type: 'cron/saveCron',
            params: values
          }).then(res => {
            if (res) {
              setVisible(false);
            }
          })
        }
      }
    });
  }

  const setCronName = (val, record) => {
    const nameValue = getFieldValue("name");
    const remarksValue = getFieldValue("remarks");
    let label = record.props.children;
    label = label.replace(val, "").replace(" （ ", "").replace(" ）", "");
    if (nameValue === undefined || nameValue.trim() === "") {
      setFieldsValue({ "name": label,});
    }
    if (remarksValue === undefined || remarksValue.trim() === "") {
      setFieldsValue({ "remarks": label,});
    }
  }

  return (
    <span>
      <Button icon="plus" type="primary" onClick={initAdd}>新增定时任务</Button>
      <Drawer
        title="新建定时任务"
        placement="right"
        closable={false}
        onClose={() => setVisible(false) }
        visible={visible}
        width={650}
      >
        <Spin spinning={loading}>
          <Form {...formItemLayout}>
            <Form.Item label="标识">
              {getFieldDecorator('mark', {
                rules: [
                  {
                    required: true,
                    message: '请选择标识',
                  },
                ],
              })(
                <Select placeholder="选择定时任务" showSearch allowClear onChange={(val, record) => setCronName(val, record)}>
                  {
                    cronSelectData.map((item, key) => (
                      <Option value={item.value} key={key}>{`${item.value} （ ${item.label} ）`}</Option>
                    ))
                  }
                </Select>
              )}
            </Form.Item>
            <Form.Item label="名称">
              {getFieldDecorator('name', {
                rules: [
                  {
                    required: true,
                    message: '请输入名称',
                  },
                ],
              })(<Input />)}
            </Form.Item>
            <Form.Item label="Cron 表达式">
              <SelectCron value={cron} render={val => setCron(val)}/>
            </Form.Item>
            <Form.Item label="备注信息">
              {getFieldDecorator('remarks', {})(<Input.TextArea placeholder="备注信息" rows={4} />)}
            </Form.Item>
          </Form>
        </Spin>

        <div
          style={{
            position: 'absolute',
            right: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
          }}
        >
          <Button onClick={() => setVisible(false)} style={{ marginRight: 8 }}>
            Cancel
          </Button>
          <Button onClick={onsubmit} type="primary">
            Submit
          </Button>
        </div>
      </Drawer>
    </span>
  )
}

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 7 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 12 },
  },
};

const form = Form.create({name: 'CronAdd',})(CronAdd)

export default connect(({cron, loading}) => ({
  loading: loading.models.cron,
  cronSelectData: cron.cronSelectData
}))(form);
